package listeners;

import dao.BaseDBAO;
import dao.ItemDBAO;
import javax.servlet.*;


// Event handler class for handling application scope events
public final class ContextListener implements ServletContextListener {
    private ServletContext context = null;

    // This method gets called when the application is deployed
    public void contextInitialized(ServletContextEvent event) {
        context = event.getServletContext();

        // Create BookDBAO object and save it as an attribute to
        // ServletContext scope object.
        try {
            BaseDBAO dBAO = new BaseDBAO();
            context.setAttribute("dB", dBAO);
            System.out.println("dB created successfully when context is newly created");
        } catch (Exception ex) {
            System.out.println("Couldn't create bookstore database bean: " + ex.getMessage());
        }
    }

    // This method gets called when the application is undeployed
    public void contextDestroyed(ServletContextEvent event) {
        context = event.getServletContext();

        BaseDBAO dBAO = (BaseDBAO) context.getAttribute("dB");

        if (dBAO != null) {
        	//Close the database connection
        	dBAO.remove();
        }

        context.removeAttribute("dB");
    }
}
